package handlers

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"strings"
	"time"

	"demo2/server/services"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

// ChatAgentHandler Agent聊天处理器
type ChatAgentHandler struct {
	chatService *services.ChatAgentService
	upgrader    websocket.Upgrader
}

// NewChatAgentHandler 创建新的Agent聊天处理器
func NewChatAgentHandler(chatService *services.ChatAgentService) *ChatAgentHandler {
	return &ChatAgentHandler{
		chatService: chatService,
		upgrader: websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				return true // 允许所有来源，生产环境应该更严格
			},
		},
	}
}

// SendMessage 发送消息
func (h *ChatAgentHandler) SendMessage(c *gin.Context) {
	log.Printf("[AGENT-HANDLER] 🤖 收到Agent消息请求，来源IP: %s", c.ClientIP())
	
	var req SendMessageRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Printf("[AGENT-HANDLER] ❌ 请求参数绑定失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	log.Printf("[AGENT-HANDLER] 📋 请求参数: 会话ID=%s, 消息长度=%d", req.SessionID, len(req.Message))
	log.Printf("[AGENT-HANDLER] 📝 用户消息内容: %s", req.Message)

	// 调用Agent聊天服务
	log.Printf("[AGENT-HANDLER] 🤖 调用Agent聊天服务处理消息...")
	response, err := h.chatService.SendMessage(c.Request.Context(), req.SessionID, req.Message)
	if err != nil {
		log.Printf("[AGENT-HANDLER] ❌ Agent聊天服务处理失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "发送消息失败"})
		return
	}

	log.Printf("[AGENT-HANDLER] ✅ Agent聊天服务处理成功，响应ID: %s", response.ID)

	// 返回响应
	responseData := SendMessageResponse{
		ID:        response.ID,
		SessionID: response.SessionID,
		Role:      response.Role,
		Content:   response.Content,
		Timestamp: response.Timestamp.Format("2006-01-02 15:04:05"),
	}
	
	log.Printf("[AGENT-HANDLER] 📤 返回响应，内容长度: %d", len(responseData.Content))
	c.JSON(http.StatusOK, responseData)
}

// SendStreamMessage 发送流式消息
func (h *ChatAgentHandler) SendStreamMessage(c *gin.Context) {
	log.Printf("[AGENT-HANDLER] 🌊 收到Agent流式消息请求")
	
	var req SendMessageRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 设置SSE头部
	c.Header("Content-Type", "text/event-stream")
	c.Header("Cache-Control", "no-cache")
	c.Header("Connection", "keep-alive")
	c.Header("Access-Control-Allow-Origin", "*")
	c.Header("Access-Control-Allow-Headers", "Cache-Control")

	// 创建响应通道
	responseChan := make(chan string, 100)
	ctx, cancel := context.WithTimeout(c.Request.Context(), 60*time.Second)
	defer cancel()

	// 启动Agent流式响应
	go func() {
		defer func() {
			// 安全关闭channel
			select {
			case <-responseChan:
			default:
				close(responseChan)
			}
		}()
		
		if err := h.chatService.SendStreamMessage(ctx, req.SessionID, req.Message, responseChan); err != nil {
			log.Printf("[AGENT-HANDLER] ❌ Agent流式响应失败: %v", err)
			select {
			case responseChan <- fmt.Sprintf(`{"error": "%s"}`, err.Error()):
			case <-ctx.Done():
			}
		}
	}()

	// 发送SSE事件
	flusher, ok := c.Writer.(http.Flusher)
	if !ok {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "不支持流式响应"})
		return
	}

	for {
		select {
		case chunk, ok := <-responseChan:
			if !ok {
				// 发送结束标记
				fmt.Fprintf(c.Writer, "data: [DONE]\n\n")
				flusher.Flush()
				return
			}
			
			// 发送数据块，格式化为JSON
			jsonData := fmt.Sprintf(`{"content": "%s"}`, strings.ReplaceAll(chunk, `"`, `\"`))
			fmt.Fprintf(c.Writer, "data: %s\n\n", jsonData)
			flusher.Flush()
			
		case <-ctx.Done():
			// 发送错误信息
			fmt.Fprintf(c.Writer, "data: {\"error\": \"请求超时\"}\n\n")
			flusher.Flush()
			return
		}
	}
}

// GetHistory 获取聊天历史
func (h *ChatAgentHandler) GetHistory(c *gin.Context) {
	sessionID := c.Param("sessionId")
	if sessionID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "sessionId是必需的"})
		return
	}

	log.Printf("[AGENT-HANDLER] 📚 获取会话历史: %s", sessionID)

	messages, err := h.chatService.GetHistory(c.Request.Context(), sessionID)
	if err != nil {
		log.Printf("[AGENT-HANDLER] ❌ 获取历史失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取历史失败"})
		return
	}

	// 转换为响应格式
	responses := make([]SendMessageResponse, len(messages))
	for i, msg := range messages {
		responses[i] = SendMessageResponse{
			ID:        msg.ID,
			SessionID: msg.SessionID,
			Role:      msg.Role,
			Content:   msg.Content,
			Timestamp: msg.Timestamp.Format("2006-01-02 15:04:05"),
		}
	}

	log.Printf("[AGENT-HANDLER] ✅ 返回 %d 条历史消息", len(responses))
	c.JSON(http.StatusOK, gin.H{"messages": responses})
}

// ClearHistory 清除聊天历史
func (h *ChatAgentHandler) ClearHistory(c *gin.Context) {
	sessionID := c.Param("sessionId")
	if sessionID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "sessionId是必需的"})
		return
	}

	log.Printf("[AGENT-HANDLER] 🗑️ 清除会话历史: %s", sessionID)

	err := h.chatService.ClearHistory(c.Request.Context(), sessionID)
	if err != nil {
		log.Printf("[AGENT-HANDLER] ❌ 清除历史失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "清除历史失败"})
		return
	}

	log.Printf("[AGENT-HANDLER] ✅ 历史清除成功")
	c.JSON(http.StatusOK, gin.H{"message": "历史已清除"})
}

// GetAgentStats 获取Agent统计信息
func (h *ChatAgentHandler) GetAgentStats(c *gin.Context) {
	log.Printf("[AGENT-HANDLER] 📊 获取Agent统计信息")
	
	stats := h.chatService.GetAgentStats()
	
	log.Printf("[AGENT-HANDLER] ✅ 返回Agent统计信息")
	c.JSON(http.StatusOK, gin.H{"stats": stats})
}

// GetAvailableTools 获取可用工具列表
func (h *ChatAgentHandler) GetAvailableTools(c *gin.Context) {
	log.Printf("[AGENT-HANDLER] 🔧 获取可用工具列表")
	
	tools := h.chatService.GetAvailableTools()
	
	log.Printf("[AGENT-HANDLER] ✅ 返回 %d 个可用工具", len(tools))
	c.JSON(http.StatusOK, gin.H{"tools": tools})
}

// WebSocketHandler WebSocket处理器
func (h *ChatAgentHandler) WebSocketHandler(c *gin.Context) {
	sessionID := c.Param("sessionId")
	if sessionID == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "sessionId是必需的"})
		return
	}

	// 升级到WebSocket连接
	conn, err := h.upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Printf("[AGENT-HANDLER] ❌ WebSocket升级失败: %v", err)
		return
	}
	defer conn.Close()

	log.Printf("[AGENT-HANDLER] 🔌 WebSocket连接建立，会话ID: %s", sessionID)

	// 处理WebSocket消息
	for {
		var msg WebSocketMessage
		err := conn.ReadJSON(&msg)
		if err != nil {
			log.Printf("[AGENT-HANDLER] ❌ 读取WebSocket消息失败: %v", err)
			break
		}

		if msg.Type == "message" && msg.Message != "" {
			log.Printf("[AGENT-HANDLER] 📨 收到WebSocket消息: %s", msg.Message)
			
			// 创建响应通道
			responseChan := make(chan string, 100)
			ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)

			// 启动Agent流式响应
			go func() {
				defer close(responseChan)
				defer cancel()
				if err := h.chatService.SendStreamMessage(ctx, sessionID, msg.Message, responseChan); err != nil {
					log.Printf("[AGENT-HANDLER] ❌ WebSocket Agent流式响应失败: %v", err)
					responseChan <- fmt.Sprintf("处理消息失败: %v", err)
				}
			}()

			// 发送流式响应
			fullResponse := ""
			for chunk := range responseChan {
				fullResponse += chunk
				err = conn.WriteJSON(WebSocketMessage{
					Type:      "stream",
					SessionID: sessionID,
					Content:   chunk,
					Role:      "assistant",
					Timestamp: time.Now().Format("2006-01-02 15:04:05"),
				})
				if err != nil {
					log.Printf("[AGENT-HANDLER] ❌ 发送WebSocket流式响应失败: %v", err)
					cancel()
					break
				}
			}

			// 发送结束标记
			if fullResponse != "" {
				err = conn.WriteJSON(WebSocketMessage{
					Type:      "end",
					SessionID: sessionID,
					Content:   fullResponse,
					Role:      "assistant",
					Timestamp: time.Now().Format("2006-01-02 15:04:05"),
				})
				if err != nil {
					log.Printf("[AGENT-HANDLER] ❌ 发送WebSocket结束消息失败: %v", err)
					break
				}
			}

			cancel()
		}
	}

	log.Printf("[AGENT-HANDLER] 🔌 WebSocket连接关闭，会话ID: %s", sessionID)
}
